const express = require('express');
const { authenticateToken } = require('../middleware/auth');
const { 
  mockDatabases, 
  mockSlowQueries, 
  mockMetrics, 
  mockStorageData 
} = require('../data/mockData');

const router = express.Router();

// Apply authentication to all routes
router.use(authenticateToken);

// Get all databases
router.get('/', (req, res) => {
  res.json({
    success: true,
    data: mockDatabases
  });
});

// Get single database
router.get('/:id', (req, res) => {
  const database = mockDatabases.find(db => db.id === req.params.id);
  
  if (!database) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  res.json({
    success: true,
    data: database
  });
});

// Create new database
router.post('/', (req, res) => {
  const { name, engine, version, instanceType, region, storage } = req.body;

  // Validate required fields
  if (!name || !engine || !version || !instanceType || !region || !storage) {
    return res.status(400).json({
      success: false,
      error: 'All fields are required'
    });
  }

  // Check if database name already exists
  const existingDb = mockDatabases.find(db => db.name === name);
  if (existingDb) {
    return res.status(409).json({
      success: false,
      error: 'Database with this name already exists'
    });
  }

  const newDatabase = {
    id: `db-${Date.now()}`,
    name,
    engine,
    version,
    status: 'pending',
    region,
    instanceType,
    storage: parseInt(storage),
    connections: 0,
    cpu: 0,
    memory: 0,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  };

  mockDatabases.push(newDatabase);

  // Simulate database becoming ready after 3 seconds
  setTimeout(() => {
    const dbIndex = mockDatabases.findIndex(db => db.id === newDatabase.id);
    if (dbIndex !== -1) {
      mockDatabases[dbIndex] = {
        ...mockDatabases[dbIndex],
        status: 'running',
        connections: Math.floor(Math.random() * 20) + 5,
        cpu: Math.floor(Math.random() * 50) + 10,
        memory: Math.floor(Math.random() * 60) + 20,
        updatedAt: new Date().toISOString()
      };
    }
  }, 3000);

  res.status(201).json({
    success: true,
    data: newDatabase
  });
});

// Update database
router.patch('/:id', (req, res) => {
  const dbIndex = mockDatabases.findIndex(db => db.id === req.params.id);
  
  if (dbIndex === -1) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  const updatedDatabase = {
    ...mockDatabases[dbIndex],
    ...req.body,
    updatedAt: new Date().toISOString()
  };

  mockDatabases[dbIndex] = updatedDatabase;

  res.json({
    success: true,
    data: updatedDatabase
  });
});

// Delete database
router.delete('/:id', (req, res) => {
  const dbIndex = mockDatabases.findIndex(db => db.id === req.params.id);
  
  if (dbIndex === -1) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  const deletedDatabase = mockDatabases.splice(dbIndex, 1)[0];

  res.json({
    success: true,
    data: deletedDatabase
  });
});

// Start database
router.post('/:id/start', (req, res) => {
  const dbIndex = mockDatabases.findIndex(db => db.id === req.params.id);
  
  if (dbIndex === -1) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  if (mockDatabases[dbIndex].status === 'running') {
    return res.status(400).json({
      success: false,
      error: 'Database is already running'
    });
  }

  mockDatabases[dbIndex] = {
    ...mockDatabases[dbIndex],
    status: 'running',
    connections: Math.floor(Math.random() * 20) + 5,
    cpu: Math.floor(Math.random() * 50) + 10,
    memory: Math.floor(Math.random() * 60) + 20,
    updatedAt: new Date().toISOString()
  };

  res.json({
    success: true,
    data: mockDatabases[dbIndex]
  });
});

// Stop database
router.post('/:id/stop', (req, res) => {
  const dbIndex = mockDatabases.findIndex(db => db.id === req.params.id);
  
  if (dbIndex === -1) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  if (mockDatabases[dbIndex].status === 'stopped') {
    return res.status(400).json({
      success: false,
      error: 'Database is already stopped'
    });
  }

  mockDatabases[dbIndex] = {
    ...mockDatabases[dbIndex],
    status: 'stopped',
    connections: 0,
    cpu: 0,
    memory: 0,
    updatedAt: new Date().toISOString()
  };

  res.json({
    success: true,
    data: mockDatabases[dbIndex]
  });
});

// Get database metrics
router.get('/:id/metrics', (req, res) => {
  const database = mockDatabases.find(db => db.id === req.params.id);
  
  if (!database) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  res.json({
    success: true,
    data: mockMetrics
  });
});

// Get current metrics
router.get('/:id/metrics/current', (req, res) => {
  const database = mockDatabases.find(db => db.id === req.params.id);
  
  if (!database) {
    return res.status(404).json({
      success: false,
      error: 'Database not found'
    });
  }

  const currentMetrics = {
    timestamp: new Date().toISOString(),
    cpu: database.cpu,
    memory: database.memory,
    connections: database.connections,
    iops: Math.floor(Math.random() * 1000) + 500
  };

  res.json({
    success: true,
    data: currentMetrics
  });
});

// Get slow queries
router.get('/slow-queries', (req, res) => {
  const { databaseId, limit = 50 } = req.query;
  
  let queries = mockSlowQueries;
  
  if (databaseId) {
    queries = queries.filter(query => query.database === databaseId);
  }
  
  queries = queries.slice(0, parseInt(limit));

  res.json({
    success: true,
    data: queries
  });
});

// Get storage usage
router.get('/storage', (req, res) => {
  const { databaseId } = req.query;
  
  let storageData = mockStorageData;
  
  if (databaseId) {
    storageData = storageData.filter(storage => storage.databaseId === databaseId);
  }

  res.json({
    success: true,
    data: storageData
  });
});

// Kill query
router.post('/slow-queries/:queryId/kill', (req, res) => {
  const queryIndex = mockSlowQueries.findIndex(q => q.id === req.params.queryId);
  
  if (queryIndex === -1) {
    return res.status(404).json({
      success: false,
      error: 'Query not found'
    });
  }

  // Simulate killing the query
  mockSlowQueries.splice(queryIndex, 1);

  res.json({
    success: true,
    message: 'Query killed successfully'
  });
});

// Optimize query
router.post('/slow-queries/:queryId/optimize', (req, res) => {
  const query = mockSlowQueries.find(q => q.id === req.params.queryId);
  
  if (!query) {
    return res.status(404).json({
      success: false,
      error: 'Query not found'
    });
  }

  const suggestions = [
    'Add an index on the user_id column',
    'Consider using LIMIT to reduce result set size',
    'Replace SELECT * with specific column names',
    'Add WHERE clause to filter results earlier'
  ];

  res.json({
    success: true,
    data: {
      suggestions: suggestions.slice(0, Math.floor(Math.random() * 3) + 1)
    }
  });
});

module.exports = router;